package com.xjj.core.modules.orm.hibernate;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.impl.CriteriaImpl;
import org.hibernate.transform.ResultTransformer;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.xjj.core.modules.commons.utils.ReflectionUtils;
import com.xjj.core.modules.orm.Condition;
import com.xjj.core.modules.orm.OrderBy;
import com.xjj.core.modules.orm.Finder;
import com.xjj.core.modules.orm.Page;
import com.xjj.core.modules.orm.PageRequest;
import com.xjj.core.modules.orm.PropertyFilter;
import com.xjj.core.modules.orm.PropertyFilter.MatchType;

/**
 * hibernate加强封装的HibernateDao基类.
 * 
 * 提供分页查询,按属性条件组合查询等功能.
 * 
 * @param <T> DAO操作的对象类型
 * @param <PK> 主键类型
 * 
 */

public class HibernateDao<T, PK extends Serializable> extends SimpleHibernateDao<T, PK> {
	
	
	//为了JSONConvert进行转换的而增加的
	public static final String ID_NAME = "id";
	
	/**
	 * 用于扩展的DAO子类使用的构造函数.
	 * 
	 * 通过子类的泛型定义取得对象类型Class.
	 * eg.
	 * public class UserDao extends HibernateDao<User, Long>{
	 * }
	 */
	public HibernateDao() {
		super();
	}
	

	public HibernateDao(SessionFactory sessionFactory) {
		super(sessionFactory);
	}

	public HibernateDao(SessionFactory sessionFactory, Class<T> entityClass) {
		super(sessionFactory, entityClass);
	}

	/**
	 * 分页获取全部对象. 
	 */
	public Page<T> findAll(final Page<T> page) {
		return findByCriteria(page);
	}
	
	/**
	 * 按属性过滤条件列表分页查找对象.
	 */
	public Page<T> find(final Page<T> page, final List<PropertyFilter> filters) {
		Criterion[] criterions = buildFilterCriterions(filters);
		return findByCriteria(page, criterions);
	}

	/**
	 * 按HQL分页查询.
	 * 不支持自动获取总结果数,需用户另行执行查询.
	 * 
	 * @param page 分页参数.仅支持pageSize 和firstResult,忽略其他参数.
	 * @param hql hql语句.
	 * @param values 数量可变的查询参数.
	 * 
	 * @return 分页查询结果,附带结果列表及所有查询时的参数.
	 */
	@SuppressWarnings("unchecked")
	public Page<T> find(final Page<T> page, final String hql, final Object... values) {
		Assert.notNull(page);
		//获取查询总数的语句
		Finder find = Finder.create(hql);
		String countQueryString = find.getRowCountHql();//" select count (*) " + removeSelect(removeOrders(hql));
		if (page.isAutoCount()) {
			//logger.warn("HQL查询暂不支持自动获取总结果数,hql语句为{}----增加可以获取总数", hql);
			Query q = createQuery(countQueryString); 
			Long count = (Long)q.uniqueResult();//可以获取到
			//logger.info("count---------- "+count);
			page.setTotalCount(count.intValue());
		}

		Query q = createQuery(hql, values);
		pagationQuery(q, page);
		List result = q.list();
		page.setResult(result);
		return page;
	}
	//变化一下注释掉的方法
	@SuppressWarnings("unchecked")
	public Page<T> findByCriteria(final Page<T> page, final Criterion... criterions) {
		Assert.notNull(page);

		Criteria c = createCriteria(criterions);

		if (page.isAutoCount()) {
			int totalCount = countCriteriaResult(c, page);
			page.setTotalCount(totalCount);
		}

		//pagationCriteria(c, page);
		setPageParameter(c, page);
		List result = c.list();
		page.setResult(result);
		return page;
	}
	
	/**
	 * 按Criteria分页查询.
	 * 
	 * @param page 分页参数.
	 * @param criterions 数量可变的Criterion.
	 * 
	 * @return 分页查询结果.附带结果列表及所有查询时的参数.
	 */
	@SuppressWarnings("unchecked")
	public Page<T> findPage(final Page<T> page, final Criterion... criterions) {
		Assert.notNull(page, "page不能为空");

		Criteria c = createCriteria(criterions);

		if (page.isAutoCount()) {
			int totalCount = countCriteriaResult(c);
			page.setTotalCount(totalCount);
		}

		setPageParameter(c, page);
		List result = c.list();
		page.setResult(result);
		return page;
	}
	
	/**
	 * 执行count查询获得本次Criteria查询所能获得的对象总数.
	 */
	@SuppressWarnings("unchecked")
	protected int countCriteriaResult(final Criteria c) {
		CriteriaImpl impl = (CriteriaImpl) c;

		// 先把Projection、ResultTransformer、OrderBy取出来,清空三者后再执行Count操作
		Projection projection = impl.getProjection();
		ResultTransformer transformer = impl.getResultTransformer();

		List<CriteriaImpl.OrderEntry> orderEntries = null;
		try {
			orderEntries = (List) ReflectionUtils.getFieldValue(impl, "orderEntries");
			ReflectionUtils.setFieldValue(impl, "orderEntries", new ArrayList());
		} catch (Exception e) {
			logger.error("不可能抛出的异常:{}", e.getMessage());
		}

		// 执行Count查询
		int totalCount = (Integer) c.setProjection(Projections.rowCount()).uniqueResult();

		// 将之前的Projection,ResultTransformer和OrderBy条件重新设回去
		c.setProjection(projection);

		if (projection == null) {
			c.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
		}
		if (transformer != null) {
			c.setResultTransformer(transformer);
		}
		try {
			ReflectionUtils.setFieldValue(impl, "orderEntries", orderEntries);
		} catch (Exception e) {
			logger.error("不可能抛出的异常:{}", e.getMessage());
		}

		return totalCount;
	}
	
	/**
	 * 设置分页参数到Query对象,辅助函数.
	 */
	protected Query setPageParameter(final Query q, final Page<T> page) {
		//hibernate的firstResult的序号从0开始
		q.setFirstResult(page.getFirst() - 1);
		q.setMaxResults(page.getPageSize());
		return q;
	}
	
	/**
	 * 设置分页参数到Criteria对象,辅助函数.
	 */
	protected Criteria setPageParameter(final Criteria c, final Page<T> page) {
		//hibernate的firstResult的序号从0开始
		c.setFirstResult(page.getFirst() - 1);
		c.setMaxResults(page.getPageSize());

		if (page.isOrderBySetted()) {
			String[] orderByArray = StringUtils.split(page.getOrderBy(), ',');
			String[] orderArray = StringUtils.split(page.getOrder(), ',');

			Assert.isTrue(orderByArray.length == orderArray.length, "分页多重排序参数中,排序字段与排序方向的个数不相等");

			for (int i = 0; i < orderByArray.length; i++) {
				if (Page.ASC.equals(orderArray[i])) {
					c.addOrder(Order.asc(orderByArray[i]));
				} else {
					c.addOrder(Order.desc(orderByArray[i]));
				}
			}
		}
		return c;
	}
	
	

	/**
	 * 按属性查找对象列表,支持多种匹配方式.
	 */
	public List<T> findByProperty(final String propertyName, final Object value, MatchType matchType) {
		Criterion criterion = buildPropertyCriterion(propertyName, value, matchType);
		return findByCriteria(criterion);
	}

	/**
	 * 按属性过滤条件列表查找对象列表.
	 */
	public List<T> findByFilters(final List<PropertyFilter> filters) {
		Criterion[] criterions = buildFilterCriterions(filters);
		return findByCriteria(criterions);
	}
	
	/**
	 * 按属性过滤条件列表分页查找对象.
	 */
	public Page<T> findPage(final Page<T> page, final List<PropertyFilter> filters) {
		Criterion[] criterions = buildPropertyFilterCriterions(filters);
		return findByCriteria(page, criterions);
	}

	/**
	 * 按属性过滤条件列表分页查找对象.
	 */
	public Page<T> findByFilters(final Page<T> page, final List<PropertyFilter> filters) {
		Criterion[] criterions = buildFilterCriterions(filters);
		return findByCriteria(page, criterions);
	}

	/**
	* 设置分页参数到Query对象,辅助函数.
	*/
	protected Query pagationQuery(final Query q, final PageRequest page) {
		q.setFirstResult(page.getFirst());
		q.setMaxResults(page.getPageSize());
		return q;
	}
	
	/**
	 * 按属性条件列表创建Criterion数组,辅助函数.
	 */
	protected Criterion[] buildPropertyFilterCriterions(final List<PropertyFilter> filters) {
		List<Criterion> criterionList = new ArrayList<Criterion>();
		for (PropertyFilter filter : filters) {
			if (!filter.isMultiProperty()) { //只有一个属性需要比较的情况.
				Criterion criterion = buildPropertyFilterCriterion(filter.getPropertyName(), filter.getValue(), filter
						.getMatchType());
				criterionList.add(criterion);
			} else {//包含多个属性需要比较的情况,进行or处理.
				Disjunction disjunction = Restrictions.disjunction();
				for (String param : filter.getPropertyNames()) {
					Criterion criterion = buildPropertyFilterCriterion(param, filter.getValue(), filter.getMatchType());
					disjunction.add(criterion);
				}
				criterionList.add(disjunction);
			}
		}
		return criterionList.toArray(new Criterion[criterionList.size()]);
	}

	/**
	 * 按属性条件参数创建Criterion,辅助函数.
	 */
	protected Criterion buildPropertyFilterCriterion(final String propertyName, final Object value,
			final MatchType matchType) {
		Assert.hasText(propertyName, "propertyName不能为空");
		Criterion criterion = null;
		try {
			//按entity property中的类型将字符串转化为实际类型.
			Object realValue = ReflectionUtils.convertValue(value, entityClass, propertyName);

			//根据MatchType构造criterion
			if (MatchType.EQ.equals(matchType)) {
				criterion = Restrictions.eq(propertyName, realValue);
			}
			if (MatchType.LIKE.equals(matchType)) {
				criterion = Restrictions.like(propertyName, (String) realValue, MatchMode.ANYWHERE);
			}
			if (MatchType.LE.equals(matchType)) {
				criterion = Restrictions.le(propertyName, realValue);
			}
			if (MatchType.LT.equals(matchType)) {
				criterion = Restrictions.lt(propertyName, realValue);
			}
			if (MatchType.GE.equals(matchType)) {
				criterion = Restrictions.ge(propertyName, realValue);
			}
			if (MatchType.GT.equals(matchType)) {
				criterion = Restrictions.gt(propertyName, realValue);
			}
		} catch (Exception e) {
			throw ReflectionUtils.convertToUncheckedException(e);
		}
		return criterion;
	}

	/**
	 * 设置分页参数到Criteria对象,辅助函数.
	 */
	protected Criteria pagationCriteria(final Criteria c, final PageRequest page) {
		c.setFirstResult(page.getFirst());
		c.setMaxResults(page.getPageSize());

		if (page.isOrderBySetted()) {
			String[] orderByArray = StringUtils.split(page.getOrderBy(), ',');
			String[] orderArray = StringUtils.split(page.getOrder(), ',');

			Assert.isTrue(orderByArray.length != orderArray.length, "分页排序参数中,排序字段与排序方向的个数不相等");

			for (int i = 0; i < orderByArray.length; i++) {
				if (PageRequest.ASC.equals(orderArray[i])) {
					c.addOrder(Order.asc(orderByArray[i]));
				} else {
					c.addOrder(Order.desc(orderByArray[i]));
				}
			}
		}
		return c;
	}

	/**
	 * 执行count查询获得本次Criteria查询所能获得的对象总数.
	 * 
	 * @return page对象中的totalCount属性将赋值.
	 */
	@SuppressWarnings("unchecked")
	protected int countCriteriaResult(final Criteria c, final PageRequest page) {
		CriteriaImpl impl = (CriteriaImpl) c;

		// 先把Projection、ResultTransformer、OrderBy取出来,清空三者后再执行Count操作
		Projection projection = impl.getProjection();
		ResultTransformer transformer = impl.getResultTransformer();

		List<CriteriaImpl.OrderEntry> orderEntries = null;
		try {
			orderEntries = (List) ReflectionUtils.getFieldValue(impl, "orderEntries");
			ReflectionUtils.setFieldValue(impl, "orderEntries", new ArrayList());
		} catch (Exception e) {
			logger.error("不可能抛出的异常:{}", e.getMessage());
		}

		// 执行Count查询
		int totalCount = (Integer) c.setProjection(Projections.rowCount()).uniqueResult();

		// 将之前的Projection,ResultTransformer和OrderBy条件重新设回去
		c.setProjection(projection);

		if (projection == null) {
			c.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
		}
		if (transformer != null) {
			c.setResultTransformer(transformer);
		}

		try {
			ReflectionUtils.setFieldValue(impl, "orderEntries", orderEntries);
		} catch (Exception e) {
			logger.error("不可能抛出的异常:{}", e.getMessage());
		}

		return totalCount;
	}

	/**
	 * 按属性条件创建Criterion,辅助函数.
	 */
	protected Criterion buildPropertyCriterion(final String propertyName, final Object value, MatchType matchType) {
		Assert.hasText(propertyName);
		Criterion criterion = null;

		if (MatchType.EQ.equals(matchType)) {
			criterion = Restrictions.eq(propertyName, value);
		}
		if (MatchType.LIKE.equals(matchType)) {
			criterion = Restrictions.like(propertyName, (String) value, MatchMode.ANYWHERE);
		}

		return criterion;
	}

	/**
	 * 按属性条件列表创建Criterion数组,辅助函数.
	 */
	protected Criterion[] buildFilterCriterions(List<PropertyFilter> filters) {
		List<Criterion> list = new ArrayList<Criterion>();
		for (PropertyFilter filter : filters) {
			String propertyName = filter.getPropertyName();

			//properName中包含'|'的情况,进行or处理.
			if (StringUtils.contains(propertyName, "|")) {

				Disjunction disjunction = Restrictions.disjunction();
				String[] params = StringUtils.split(propertyName, '|');

				for (String param : params) {
					Criterion criterion = buildPropertyCriterion(param, filter.getValue(), filter.getMatchType());
					disjunction.add(criterion);
				}
				list.add(disjunction);
				break;
			}

			//普通情况
			Criterion criterion = buildPropertyCriterion(propertyName, filter.getValue(), filter.getMatchType());
			list.add(criterion);
		}
		return list.toArray(new Criterion[list.size()]);
	}
	
	
	//下面两个findAll方法来
	//参数修改：int pageNo, int pageSize ----> final int pageNo, final int pageSize,
	//原OrderBy... orders--->final OrderBy... orders
	//同时要增加findByCriteria方法
	//修改Pagination类 ---> Page<T>类
	public Page<T> findAll(final int pageNo, final int pageSize,final OrderBy... orders) {
		Criteria crit = createCriteria();
		return findByCriteria(crit, pageNo, pageSize, null, OrderBy.asOrders(orders));
	}
	
//	为上面的查询增加这个方法---protected类型为public
	//参数修改：前面全部增加final
	//修改Pagination类 ---> Page类
	@SuppressWarnings("unchecked")
	public Page<T> findByCriteria(final Criteria crit,final int pageNo,
			final int pageSize, final Projection projection, final Order... orders) {
		int totalCount = (Integer) crit.setProjection(Projections.rowCount())
				.uniqueResult();
		//在Page中增加Page(pageNo, pageSize, totalCount)构造函数
		Page p = new Page(pageNo, pageSize, totalCount);
		if (totalCount < 1) {
			//p.setList--->p.setResult
			p.setResult(new ArrayList());
			return p;
		}
		crit.setProjection(projection);
		if (projection == null) {
			crit.setResultTransformer(Criteria.ROOT_ENTITY);
		}
		if (orders != null) {
			for (Order order : orders) {
				crit.addOrder(order);
			}
		}
		//p.getFirstResult()---> p.getFirst()
		crit.setFirstResult(p.getFirst());
		crit.setMaxResults(p.getPageSize());
		//p.setList--->p.setResult
		p.setResult(crit.list());
		return p;
	}
	
	
//	下面增加一个findBy 方法------> 
	/**
	 * 
	 * 修改方法类型：protected----> public
	 * 修改参数: 参数前面全部增加：final
	 * 修改类Pagination------>Page<T>
	 * 增加Finder 类
	 */
	@SuppressWarnings("unchecked")
	public Page<T> findByFinder(final Finder finder, final int pageNo, final int pageSize) {
		this.logger.info("findByFinder--------------");
		/*Long date0 = System.currentTimeMillis();
		this.logger.info("测试百万数据查询  0:: "+date0);*/
		int totalCount = countQueryResult(finder);
		/*Long date00 = System.currentTimeMillis();
		this.logger.info("测试获取tatalCount的时间:: "+(date00-date0));
		this.logger.info("totalCount------- "+totalCount);*/
		//修改这个构造函数
		Page p = new Page(pageNo, pageSize, totalCount);
		if (totalCount < 1) {
			//p.setList--->p.setResult
			p.setResult(new ArrayList());
			return p;
		}
		/*Long date1 = System.currentTimeMillis();
		this.logger.info("测试百万数据查询  1:: "+(date1-date0));*/
		Query query = getSession().createQuery(finder.getOrigHql());
		/*Long date2 = System.currentTimeMillis();
		this.logger.info("测试百万数据查询  2:: "+(date2-date1));*/
		finder.setParamsToQuery(query);
		/*Long date3 = System.currentTimeMillis();
		this.logger.info("测试百万数据查询  3:: "+(date3-date1));*/
		//p.getFirstResult()--->
		query.setFirstResult(p.getFirst());
		/*Long date4 = System.currentTimeMillis();
		this.logger.info("测试百万数据查询  4:: "+(date4-date1));*/
		query.setMaxResults(p.getPageSize());
		/*Long date5 = System.currentTimeMillis();
		this.logger.info("测试百万数据查询  5:: "+(date5-date1));*/
		List list = query.list();
		/*Long date6 = System.currentTimeMillis();
		this.logger.info("测试百万数据查询  6:: "+(date6-date1));*///191687  这里真她们的靠时间阿，越是往后，越是慢
		//p.setList--->p.setResult
		p.setResult(list);
		/*Long date7 = System.currentTimeMillis();
		this.logger.info("测试百万数据查询  7::: "+(date7-date1));
		this.logger.info("using memory is： "+ java.lang.Runtime.getRuntime().totalMemory() / 1024 + "K");*/
		return p;
	}
	
	
	@SuppressWarnings("unchecked")
	protected List find(Finder finder) {
		Query query = getSession().createQuery(finder.getOrigHql());
		finder.setParamsToQuery(query);
		query.setFirstResult(finder.getFirstResult());
		if (finder.getMaxResults() > 0) {
			query.setMaxResults(finder.getMaxResults());
		}
		List list = query.list();
		return list;
	}
	
	/**
	 * 
	 * 修改方法类型：protected----> public
	 * 修改参数: 参数前面全部增加：final
	 * 修改类
	 * 增加Finder 类
	 */
	 @SuppressWarnings("unchecked")
	public List<T> findByFinder(final Finder finder) {
		int totalCount = countQueryResult(finder);
		if (totalCount < 1) {
			return new ArrayList();
		}
		Query query = getSession().createQuery(finder.getOrigHql());
		finder.setParamsToQuery(query);
		query.setFirstResult(finder.getFirstResult());
		query.setMaxResults(finder.getMaxResults());
		List list = query.list();
		
		return list;
	}
	/**
	 * 
	 * 修改方法类型：protected----> public
	 * 修改参数: 参数前面全部增加：final
	 * 修改类
	 * 增加Finder 类
	 */
	@SuppressWarnings("unchecked")
	public List<T> findByEgList(final T eg, boolean anyWhere, final Condition[] conds,
			String... exclude) {
		Criteria crit = getCritByEg(eg, anyWhere, conds, exclude);
		return crit.list();
	}

	/**
	 * 
	 * 修改方法类型：protected----> public
	 * 修改参数: 参数前面全部增加：final
	 * 修改类
	 * 增加Finder 类
	 */
	@SuppressWarnings("unchecked")
	public List<T> findByEgList(final T eg, final boolean anyWhere, final Condition[] conds,
			int firstResult, int maxResult, String... exclude) {
		Criteria crit = getCritByEg(eg, anyWhere, conds, exclude);
		crit.setFirstResult(firstResult);
		crit.setMaxResults(maxResult);
		return crit.list();
	}

	/**
	 *
	 * 修改方法类型：protected----> public
	 * 修改参数: 参数前面全部增加：final
	 * 修改类Pagination---Page<T>
	 * 增加Finder 类
	 * 
	 */
	public Page<T> findByEg(final T eg, final boolean anyWhere, final Condition[] conds,
			int page, int pageSize, String... exclude) {
		Criteria crit = getCritByEg(eg, anyWhere, conds, exclude);
		return findByCriteria(crit, page, pageSize, null);
	}
	
	@Transactional(readOnly = true)
	public List<T> findByEgList(T eg, Condition[] conds, String... exclude) {
		return this.findByEgList(eg, false, conds, exclude);
	}
	
	
	@Transactional(readOnly = true)
	public List<T> findByEgList(T eg, Condition[] conds, int firstResult,
			int maxResult, String... exclude) {
		return this.findByEgList(eg, false, conds, firstResult, maxResult,
				exclude);
	}
	
}
